﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Amie
{
    public partial class FrmConStr : Form
    {
        private ProductInfo _info;
        public FrmConStr(ProductInfo info)
        {
            InitializeComponent();
            _info = info;
        }

        private void FrmConStr_Load(object sender, EventArgs e)
        {
            LoadFormFromConnection();
        }

        private void LoadFormFromConnection()
        {
            if (_info.ConnectionString == null) return;

            txtServer.Text = _info.ConnectionString.DataSource;
            txtDatabase.Text = _info.ConnectionString.InitialCatalog;
            txtUser.Text = _info.ConnectionString.UserID;
            txtPassword.Text = _info.ConnectionString.Password;
            cboxIntegrated.Checked = _info.ConnectionString.IntegratedSecurity;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {

            LoadConnectionFromForm();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void LoadConnectionFromForm()
        {
            if (_info.ConnectionString == null) _info.ConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder();
            _info.ConnectionString.DataSource = txtServer.Text;
            _info.ConnectionString.InitialCatalog = txtDatabase.Text;
            _info.ConnectionString.UserID = txtUser.Text;
            _info.ConnectionString.Password = txtPassword.Text;
            _info.ConnectionString.IntegratedSecurity = cboxIntegrated.Checked;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btnTestConString_Click(object sender, EventArgs e)
        {
            LoadConnectionFromForm();
            DB.SchemaChangeApi dbapi = new DB.SchemaChangeApi(_info);

            var result = dbapi.TestDatabaseConnection();
            if (result.Success)
                MessageBox.Show("Success", "Database Connection Test");
            else
                MessageBox.Show(string.Format("Connection to the database failed with this exception message {0}. ",result.Message), "Database Connection Test");
        }



    }
}
